<template>
	<view class="pb-safe-area">
		<image :src="info.poster" :style="posterSize" v-if="showPoster" mode="scaleToFill" show-menu-by-longpress
			@longpress="saveFile" />
		<x-loading v-if="!showPoster" />
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { usePlatformStore, useRefs } from "@/stores";
import { $helper, $api, $message } from "@/utils";
const PlatformStore = usePlatformStore();
const { PLATFORM } = useRefs(PlatformStore);
const sInfo = $helper.info();
const posterSize = ref({
	width: `${sInfo.windowWidth}px`,
	height: '0px'
});
const showPoster = ref(false);
const info = ref({});
const getDealer = () => {
	$api.Dealer.getPoster({
		platform: PLATFORM.value.platform
	}).then((data: any) => {
		info.value = data;
		uni.getImageInfo({
			src: data.poster,
			success: (res: any) => {
				const scale = sInfo.windowWidth / res.width;
				posterSize.value.height = `${res.height * scale}px`;
				showPoster.value = true;
			},
			fail: (err: any) => {
				posterSize.value.height = `${sInfo.windowHeight - sInfo.windowTop}px`;
				showPoster.value = true;
			}
		})
	}).catch((err: any) => {
		$message.error(err.msg);
	})
}
const saveFile = () => {
	// #ifdef APP
	uni.showActionSheet({
		title: '邀新有礼',
		itemList: ['复制链接', '保存图片至相册'],
		success: (res: any) => {
			switch (res.tapIndex) {
				case 0:
					uni.setClipboardData({
						data: info.value.link,
						success: () => {
							$message.success('复制成功');
						},
						fail: () => {
							$message.error('复制失败');
						}
					})
					break;
				case 1:
					uni.downloadFile({
						url: info.value.poster,
						success: (res: any) => {
							$helper.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									$message.success('保存成功');
								},
								fail: () => {
									$message.error('保存失败');
								}
							})
						},
						fail: () => {
							$message.error('保存失败');
						}
					})
					break;
			}
		}
	})
	// #endif
}
onLoad(() => {
	getDealer();
})
</script>

<style lang="scss" scoped></style>
